#include<unistd.h>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<pthread.h>

const int num=5;

using namespace std;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* active(void* args)
{
    string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        //假设该线程因为某种条件满足，所以把该线程放进条件变量等待
        pthread_cond_wait(&cond,&mutex);//pthread_cond_wait调用的时候会自动释放锁，否则该线程就是抱着锁等待了，这样其它线程也访问不了临界资源，饥饿问题也没有解决
        //排队就是让多线程按一定的顺序访问临界资源
        cout<<name<< "活动"<<endl;
        pthread_mutex_unlock(&mutex);
    }
}
int main()
{
    pthread_t tids[num];
    for(int i=0;i<num;i++)
    {
        char* name = new char[32];
        snprintf(name,32,"thread-%d",i+1);
        pthread_create(tids+i,nullptr,active,name);
    }
    sleep(3);

    while(true)
    {
        //依次唤醒线程
        cout << "main thread wakeup thread..."<<endl;
        pthread_cond_signal(&cond);
        //也可以一次性唤醒所有线程
        //pthread_cond_broadcast(&cond);
        sleep(1);
    }
    for(int i=0;i<num;i++)
    {
        pthread_join(tids[i],nullptr);
    }
    return 0;
}
